﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Controller;
using Interfaces;
using Model;
using System.Collections;


// Print
using System.Drawing.Imaging;
using System.IO;

namespace GUI
{
    public partial class TurneringsKort : Form
    {
        private System.IO.Stream streamToPrint;


        #region Attributes
        TurneringsSystem control;
        IDeltager aktuelDeltager;
        ITurnering aktuelTurnering;
        #endregion

        #region Constructor
        public TurneringsKort(TurneringsSystem control, int deltagerID, int turneringsID)
        {
            InitializeComponent();
            this.control = control;
            aktuelTurnering = control.FindTurnering(turneringsID);
            aktuelDeltager = control.FindDeltager(deltagerID);
            LoadDeltager();
            btnPrint.Focus();
        }
        #endregion


        #region Methods
        private void LoadDeltager()
        {
            lblNummer.Text = aktuelDeltager.Nr.ToString();
            lblGruppe.Text = aktuelTurnering.Gruppenavn;
            if (aktuelDeltager.Rating != 0)
            {
                lblRating.Text = aktuelDeltager.Rating.ToString();
            }
            lblNavn.Text = aktuelDeltager.Navn + " " + aktuelDeltager.Efternavn;
            lblKlub.Text = aktuelDeltager.Klub;

            IRunde rundedata;
            IEnumerator rundeiterator = control.GetRundeIterator();
            rundeiterator.Reset();

            int rundteantal = 0;
            while (rundeiterator.MoveNext())
            {                
                rundedata = (IRunde)rundeiterator.Current;
                rundteantal++;
            }
            rundeiterator.Reset();
            while (rundeiterator.MoveNext())
            {
                string farve;
                rundedata = (IRunde)rundeiterator.Current;

                if (rundedata.Farve == 0)
                    farve = "S";
                else
                    farve = "H";
                
                this.Controls.Find("lblR" + rundedata.RundeNr + "F1", true)[0].Text = rundedata.Modstander.ToString();
                this.Controls.Find("lblR" + rundedata.RundeNr + "F2", true)[0].Text = farve;

                if (rundedata.RundeNr != rundteantal)
                {
                    if (rundedata.Resultat == 0.5)
                    {
                        this.Controls.Find("lblR" + rundedata.RundeNr + "F3", true)[0].Text = "½";
                    }
                    else
                    {
                        this.Controls.Find("lblR" + rundedata.RundeNr + "F3", true)[0].Text = rundedata.Resultat.ToString();
                    }

                    if ((rundedata.Ialt % 1) == 0.5)
                    {
                        string heltal = (rundedata.Ialt - 0.5).ToString();
                        if (heltal == "0")
                        {
                            heltal = "";
                        }
                        this.Controls.Find("lblR" + rundedata.RundeNr + "F4", true)[0].Text = heltal + "½";
                    }
                    else
                    {
                        this.Controls.Find("lblR" + rundedata.RundeNr + "F4", true)[0].Text = rundedata.Ialt.ToString();
                    }

                    this.Controls.Find("lblR" + rundedata.RundeNr + "F5", true)[0].Text = rundedata.Placering.ToString();
                }
                
            }

            
        }
        #endregion

        private void btnLuk_Click(object sender, EventArgs e)
        {            
            this.Close();
        }

        [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
        private static extern bool BitBlt
        (
            IntPtr hdcDest, // handle to destination DC
            int nXDest, // x-coord of destination upper-left corner
            int nYDest, // y-coord of destination upper-left corner
            int nWidth, // width of destination rectangle
            int nHeight, // height of destination rectangle
            IntPtr hdcSrc, // handle to source DC
            int nXSrc, // x-coordinate of source upper-left corner
            int nYSrc, // y-coordinate of source upper-left corner
            System.Int32 dwRop // raster operation code
        );

        private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(this.streamToPrint);
            int x = e.MarginBounds.X;
            int y = e.MarginBounds.Y;
            int width = image.Width;
            int height = image.Height;
            if ((width / e.MarginBounds.Width) > (height / e.MarginBounds.Height))
            {
                width = e.MarginBounds.Width;
                height = image.Height * e.MarginBounds.Width / image.Width;
            }
            else
            {
                height = e.MarginBounds.Height;
                width = image.Width * e.MarginBounds.Height / image.Height;
            }
            System.Drawing.Rectangle destRect = new System.Drawing.Rectangle(x, y, width, height);
            e.Graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel);
        }
        
        private void PrintScreenShot()
        {           
            Graphics g1 = this.CreateGraphics();
            Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
            Graphics g2 = Graphics.FromImage(MyImage);
            IntPtr dc1 = g1.GetHdc();
            IntPtr dc2 = g2.GetHdc();
            BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
            g1.ReleaseHdc(dc1);
            g2.ReleaseHdc(dc2);
            MyImage.Save("Spiller.Bmp", ImageFormat.Bmp);
            FileStream fileStream = new FileStream("Spiller.Bmp", FileMode.Open, FileAccess.Read);            
            fileStream.Close();                
        }

        private void btnPrint_Click_1(object sender, EventArgs e)
        {
            
            PrintScreenShot();
            SamleKortTilEtPrint();
          
            this.Close();
        }

        

        // Sammensætter billeder til 1 billede.
        public static System.Drawing.Bitmap Combine(string[] files)
        {
            //read all images into memory
            List<System.Drawing.Bitmap> images = new List<System.Drawing.Bitmap>();
            System.Drawing.Bitmap finalImage = null;
            try
            {

                int width = 0;
                int height = 0;

                foreach (string image in files)
                {
                    //create a Bitmap from the file and add it to the list
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image);

                    //Opdater størrelsen på det endelig bitmap
                    width = bitmap.Width;
                    height += bitmap.Height;

                    images.Add(bitmap);
                }


                //create a bitmap to hold the combined image
                finalImage = new System.Drawing.Bitmap(width, height);

                //get a graphics object from the image so we can draw on it
                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage))
                {
                    //set background color
                    g.Clear(System.Drawing.Color.Black);

                    //go through each image and draw it on the final image
                    int offset = 0;
                    foreach (System.Drawing.Bitmap image in images)
                    {
                        g.DrawImage(image, new System.Drawing.Rectangle(0, offset, image.Width, image.Height));
                        offset += image.Height;
                    }
                }

                return finalImage;
            }
            catch (Exception ex)
            {
                if (finalImage != null)
                    finalImage.Dispose();
                throw ex;
            }


            finally
            {
                //Ryd op i memory
                foreach (System.Drawing.Bitmap image in images)
                {
                    image.Dispose();
                }
            }
        }

        // Samler billeder til 1 billede.
        private void SamleKortTilEtPrint()
        {
            System.Drawing.Bitmap turneringsKortPrint;

            //get all the files in a directory
            string[] filesmidlertidig = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.bmp");
            string[] files = new string[(filesmidlertidig.Length + 1)];
            filesmidlertidig.CopyTo(files, 0);

            try
            {
                files[(files.Length - 1)] = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.jpg")[0];
                turneringsKortPrint = Combine(files);
            }
            catch
            {
                turneringsKortPrint = Combine(filesmidlertidig);
            }

            //save the new image
            turneringsKortPrint.Save("turneringsKortPrint.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            System.IO.File.Delete("Spiller.Bmp");
        }

        
             
    }
}
